package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.proof.face

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.Matrix
import android.os.Build
import android.os.Bundle
import android.util.Size
import android.view.View
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.core.resolutionselector.ResolutionSelector
import androidx.camera.core.resolutionselector.ResolutionStrategy
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.exifinterface.media.ExifInterface
import androidx.lifecycle.ViewModelProvider
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication

import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityCameroonProofFaceDoingBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.hitPointCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.imageUtil.ImageConvert
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog
import java.io.File
import java.io.IOException

const val REQUEST_CODE_ACTIVITY_FACE_DOING = 102

@SuppressLint("CustomSplashScreen")
class ProofCameroonFaceDoingActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var proofOcrViewModel: ProofCameroonFaceViewModel
    private lateinit var binding: ActivityCameroonProofFaceDoingBinding

    private var imageCapture: ImageCapture? = null
    private var imageOutputPath: String = outFilePath()

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        proofOcrViewModel = ViewModelProvider(this)[ProofCameroonFaceViewModel::class.java]

        // 关联布局
        binding = ActivityCameroonProofFaceDoingBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 设置全屏
        fullScreen()

        // 用到的控件
        val hotline = binding.navbarRight
        val back = binding.navbarLeft

        // 页面UI状态接口监听


        // 流程接口监听


        // 页面需要跳转监听


        // 点击确定拍照
        binding.takePicture.setOnClickListener {
            val imageCapture = imageCapture ?: return@setOnClickListener
            val outputOptions = ImageCapture.OutputFileOptions
                .Builder(File(imageOutputPath))
                .build()

            imageCapture.takePicture(
                outputOptions,
                ContextCompat.getMainExecutor(this),
                object : ImageCapture.OnImageSavedCallback {
                    override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                        try {
                            //压缩图片
                            ImageConvert.startConvertImage(File(imageOutputPath)) { localPath, thumpImg ->
                                imageOutputPath = localPath
                                val result = thumpImg//rotateBitmap(thumpImg, localPath)

                                //重置UI
                                if (result != null) {
                                    binding.imageResult.visibility = View.VISIBLE
                                    binding.imageResult.setImageBitmap(result)

                                    binding.takePicture.visibility = View.GONE
                                    binding.resultActionBg.visibility = View.VISIBLE
                                }
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }

                    override fun onError(exception: ImageCaptureException) {
                        println("Photo capture failed: ${exception.message}")
                    }
                }
            )

            // update action buttons display
            binding.resultActionBg.visibility = View.VISIBLE
            binding.takePicture.visibility = View.GONE
        }

        // 点击重拍
        binding.retake.setOnClickListener {
            binding.imageResult.setImageBitmap(null)
            binding.imageResult.visibility = View.GONE
            binding.resultActionBg.visibility = View.GONE
            binding.takePicture.visibility = View.VISIBLE
        }

        // 点击使用该图
        binding.usePicture.setOnClickListener {
            val resultIntent = Intent()
            resultIntent.putExtra("imageOutputPath", imageOutputPath)
            setResult(Activity.RESULT_OK, resultIntent)
            finish()
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
        }

        // 点击返回
        back.setOnClickListener {
            finish()
        }

        // 请求权限
        if (!askCameraPermission()) {
            openCameraPreview()
        }
    }

    /**
     * 请求相机权限
     */
    private fun askCameraPermission(): Boolean {
        val list = mutableListOf(android.Manifest.permission.CAMERA)
        if (checkPermissionsGranted(list)) {
            return false
        }
        // 未同意权限
        EasyPermissions.requestPermissions(
            this,
            "App will request Camera Permission",
            100,
            *(list.toTypedArray())
        )
        return true
    }

    /**
     * 检查权限是否同意
     */
    private fun checkPermissionsGranted(permissionList: List<String>): Boolean {
        val isNotAllGranted = permissionList.any {
            PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, it)
        }
        return !isNotAllGranted
    }

    /**
     * 启动相机预览
     */
    private fun openCameraPreview() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener({
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .build()
                .also {
                    it.setSurfaceProvider(binding.previewView.surfaceProvider)
                }

            //设置预览尺寸
            val screenWidth = resources.displayMetrics.widthPixels// binding.previewView.width
            val screenHeight = resources.displayMetrics.heightPixels//binding.previewView.height
            val resolutionStrategy = ResolutionStrategy(
                Size(screenHeight, screenWidth),
                ResolutionStrategy.FALLBACK_RULE_CLOSEST_HIGHER_THEN_LOWER
            )
            val resolutionSelector = ResolutionSelector.Builder()
                .setResolutionStrategy(resolutionStrategy)
                .build()

            imageCapture = ImageCapture.Builder()
                .setResolutionSelector(resolutionSelector)
                .build()

            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageCapture)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 输出路径
     */
    private fun outFilePath(): String {
        val imgDir = "${
            ProjectApplication.context.applicationContext.filesDir
        }${File.separator}${ProjectApplication.mProduct}_IAGS"

        val dirFile = File(imgDir)
        if (!dirFile.exists()) {
            dirFile.mkdirs()
        }

        return "$imgDir/${System.currentTimeMillis()}.jpg"
    }

    /**
     * 根据角度反转图片
     */
    fun rotateBitmap(bitmap: Bitmap, imageFilePath: String?): Bitmap? {
        try {
            val exif = ExifInterface(
                imageFilePath!!
            )
            val orientation = exif.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_UNDEFINED
            )
            val matrix = Matrix()
            when (orientation) {
                ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.setScale(-1f, 1f)
                ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f)
                ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
                    matrix.setRotate(180f)
                    matrix.postScale(-1f, 1f)
                }

                ExifInterface.ORIENTATION_TRANSPOSE -> {
                    matrix.setRotate(90f)
                    matrix.postScale(-1f, 1f)
                }

                ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
                ExifInterface.ORIENTATION_TRANSVERSE -> {
                    matrix.setRotate(-90f)
                    matrix.postScale(-1f, 1f)
                }

                ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(-90f)
                else -> return bitmap
            }
            return try {
                val rotatedBitmap =
                    Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
                bitmap.recycle()
                rotatedBitmap
            } catch (e: OutOfMemoryError) {
                e.printStackTrace()
                null
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return bitmap
    }

    // ------> EasyPermissions <------
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        askCameraPermission()
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        openCameraPreview()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            askCameraPermission()
        }
    }

    /**
     * 设置全屏
     */
    private fun fullScreen() {
        // 设置全屏
        window.decorView.systemUiVisibility =
            (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = Color.TRANSPARENT
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.decorView.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
    }

    override fun onResume() {
        super.onResume()
        hitPointCameroon(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPointCameroon(type = this::class.java.simpleName, isPageEnd = true)
    }
}